﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using eLearning.Util;

namespace eLearning.DosenView
{
    public partial class QuestionSelectPage : PhoneApplicationPage
    {
        private QuestionList listSoal = new QuestionList();
        private Question selectedSoal;
        private Quiz quiz;

        public QuestionSelectPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.QUIZ))
            {
                quiz = (Quiz)PhoneApplicationService.Current.State[Config.QUIZ];
                LoadQuestionList(quiz.DetMatkul);
            }

        }

        private void LoadQuestionList(DetailMatkul detMatkul)
        {
            string url = string.Format("{0}&{1}", Config.Instance.QUESTION_SERVICE_URL() + Config.VIEW_ACTION_KEY, Guid.NewGuid().ToString());
            string json = JsonConvert.SerializeObject(detMatkul);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listQuestion_UploadStringCompleted);
            try
            {
                webClient.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void listQuestion_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                int noUrut = 1;
                listQuestion.Items.Clear();
                QuestionList soals = JsonConvert.DeserializeObject<QuestionList>(e.Result);
                foreach (Question ques in soals)
                {
                    ques.NoUrut = Convert.ToString(noUrut + ".");
                    listQuestion.Items.Add(ques);
                    noUrut++;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SaveQuiz(QuestionList data)
        {
            string url = Config.Instance.QUESTION_SERVICE_URL() + Config.SAVE_ACTION_KEY; //update
            string json = JsonConvert.SerializeObject(data);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(saveChange_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void saveChange_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(e.Result))
                {
                    if(!e.Result.Contains("Success"))
                        selectedSoal.Id = e.Result;
                    MessageBox.Show("Data Saved.");
                }
                else
                {
                    MessageBox.Show("ERROR : " + e.Result);
                }
                NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void listQuiz_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                selectedSoal = (Question)e.AddedItems[0];
                selectedSoal.Quis = quiz;
                listSoal.Add(selectedSoal);
            }
            else
            {
                listSoal.Remove(selectedSoal);
            }
        }

        private void saveButton_Click(object sender, System.EventArgs e)
        {
            SaveQuiz(listSoal);
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            LoadQuestionList(quiz.DetMatkul);
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

        private void menuCreate_Click(object sender, EventArgs e)
        {
            Utility.GotoPage(this, "/View/Dosen/QuestionPage.xaml");
        }
        
    }
}